package common.utils.sound;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;

public class MediaPlayerUtils {

	private static MediaPlayer mediaPlayer = null;
	
	public static void playSound(Context context, int resId) {

		mediaPlayer = MediaPlayer.create(context, resId);
		
		mediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
		
		int volume = getMaxVolume(context);
		
		mediaPlayer.setVolume(volume, volume);

		mediaPlayer
				.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
					@Override
					public void onCompletion(MediaPlayer mp) {
						mp = null;
						mediaPlayer = null;
					}
				});
		
		if (!mediaPlayer.isPlaying()) {
			mediaPlayer.start();
		}
	}
	
	
	public static void playSound(Context context, String resId) {
//		System.out.println(context.getPackageName());
//		System.out.println(context.getResources().getIdentifier(resId, "raw", context.getPackageName()));
		String id = null;
		if(resId.indexOf(".")>0){
			id = resId.substring(0, resId.indexOf("."));
		}
		playSound(context,context.getResources().getIdentifier(id, "raw", context.getPackageName()));
	}
	
	private static int maxVolume = 0;
	private static int currentVolume = 0;
	private static AudioManager audioManager = null;
	private static int getMaxVolume(Context context){
		if(audioManager == null){
			audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		}
		
		currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_RING );
		maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_RING );
		audioManager = null;
		if(currentVolume<Math.ceil(maxVolume*0.3)){
			currentVolume = (int) (maxVolume*0.3);
		}
		return currentVolume;
		
	}

}
